use anyhow::Result;
use rand::Rng;
use std::thread;
use std::time::Duration;
use template::metrics::cmap::MetricsDash;

const N: usize = 10;
const M: usize = 10;

fn main() -> Result<()> {
    let metrics = MetricsDash::new();

    for idx in 0..N {
        task_worker(idx, metrics.clone())?; //Arc::clone(&metrics.data)
    }

    for _ in 0..M {
        request_worker(metrics.clone())?;
    }

    loop {
        thread::sleep(Duration::from_millis(1000));
        println!("{:?}", metrics.snapshot());
    }

    // Ok(())
}

fn task_worker(idx: usize, metrics: MetricsDash) -> Result<()> {
    thread::spawn(move || loop {
        let mut rng = rand::rng();
        let sleep_time = rng.random_range(100..500);
        //do long term stuff
        thread::sleep(Duration::from_millis(sleep_time));
        metrics.inc(format!("call.thread.worker.{idx}"));
    });
    Ok(())
}

fn request_worker(metrics: MetricsDash) -> Result<()> {
    thread::spawn(move || loop {
        let mut rng = rand::rng();
        thread::sleep(Duration::from_millis(rng.random_range(50..800)));
        let page = rng.random_range(1..256);
        metrics.inc(format!("req.page.{page}"));
    });
    Ok(())
}
